package com.flickr.widgets;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.flickr.R;
import com.flickr.api.ImageURL;
import com.flickr.api.photos.Photo;
import com.flickr.tasks.BitmapLoaderTask;

public class PhotoFragment extends Fragment
{
    private static final String PHOTO_KEY = "photo";

    private Photo mPhoto;

    public PhotoFragment()
    {
        super();
    }

    public static PhotoFragment newInstance(Photo photo) {
        PhotoFragment fragment = new PhotoFragment();
        fragment.mPhoto = photo;
        return fragment;
    }

    @Override
    public void onSaveInstanceState(Bundle outState)
    {
        super.onSaveInstanceState(outState);
        if (mPhoto != null && outState != null) {
            outState.putSerializable(PHOTO_KEY, mPhoto);
        }
    }

    @Override
    public void onStart()
    {
        super.onStart();
        
        View view = getView();
        ImageView imageView = (ImageView) view.findViewById(R.id.galleryPhotoFragmentImage);
        TextView textView = (TextView) view.findViewById(R.id.galleryPhotoFragmentTitle);
        
        if(mPhoto != null) {
            new BitmapLoaderTask(mPhoto.getUrl().toURL(ImageURL.MEDIUM_1024), imageView, 2).execute();
            textView.setText(mPhoto.getTitle());
            
        } else {
            imageView.setImageDrawable(null);
            textView.setText(null);
        }
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View view = inflater.inflate(R.layout.gallery_photo_fragment, null);
        if (savedInstanceState != null) {
            mPhoto = (Photo) savedInstanceState.getSerializable(PHOTO_KEY);
        }
        return view;
    }

}
